import Food from "./Food";
import Score from "./Score";
import Snake from "./Snake";

class Gamecontrol {
    Food
    Score
    Snake
    direction:string = ''
    isalive = true
    constructor() {
        this.Food = new Food()
        this.Score = new Score(2,10)
        this.Snake = new Snake()
        this.init()
        
    }

    init(){
        document.addEventListener('keydown',this.keydownHandler.bind(this))
        this.run()
    }
    keydownHandler(event:KeyboardEvent){
        this.direction = event.key     
        console.log(this.direction);
              
    }

    run(){
        let Y = this.Snake.Y
        let X = this.Snake.X

        

        switch (this.direction) {
            case "ArrowUp":
            case "Up":
                Y -= 10
                break;
            case "ArrowDown":
            case "Down":
                Y += 10
                break;
            case "a":
                X -= 10
                break;
            case "ArrowRight":
            case "Right":
                X += 10
                break;
        }
        this.checkfood(X,Y)

        try {
            this.Snake.Y = Y
            this.Snake.X = X
        } catch (e) {
            alert(e);
            this.isalive = false
        }
        this.isalive&&setTimeout(this.run.bind(this), 300 - (this.Score.level-1)*30);
    }
    checkfood(X:Number,Y:Number){
        if( X=== this.Food.X && this.Food.Y === Y){
            this.Food.change()
            this.Score.scoreUp()
            this.Snake.addBody()
        }
    }
   
}

export default Gamecontrol
